package com.sim.contact.tool.contacts;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

import com.sim.contact.tool.utils.Log;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.TextUtils;

public class ContactAPISdk5 extends ContactAPI {

	private ContentResolver	cr;

	public ContentResolver getCr() {
		
		
		return cr;
	}

	public void setCr(ContentResolver cr) {
		this.cr = cr;
	}

	public Intent getContactIntent() {
		return (new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI));
	}

	public ContactList getSIMContactList() {
		Uri uri = Uri.parse("content://icc/adn"); 
		ContactList contacts = new ContactList();
		String id;

		Cursor cur = cr.query(uri, null, null, null, null);
		if (cur.getCount() > 0) {
			while (cur.moveToNext()) {
				Contact c = new Contact();
				id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
				c.setId(id);
				String name=null;
				String number=null;
				if(cur.getColumnCount()>0){
					name = cur.getString(0);
					number = cur.getString(1);
					
					Log.d("SIM", name+","+number);
				}else{
					continue;
				}
				c.setDisplayName(name);
				
				ArrayList<Phone> phones = new ArrayList<Phone>();
				phones.add(new Phone(number, Phone.SIM));
				c.setPhone(phones);
				
				contacts.addContact(c);
			}
		}
		if(cur!=null){
			cur.close();
		}
		return contacts;
	}

	public int addSIMContacts(ContactList contacts) {
		int rslt =0;
		if(contacts!=null && contacts.getContacts()!=null && contacts.getContacts().size()>0){
			for (Contact contact : contacts.getContacts()) {
				Uri uriTmp = addSIMContact(contact);
				if(uriTmp!=null){
					rslt ++;
				}
			}
		}
		return rslt;
	}
	/***
	 * 添加联系人到SIM 卡，name为null or ''时，使用number作为name, 第一个phone不能为空，且number不能为空;
	 * @param contact
	 * @return
	 */
	public Uri addSIMContact(Contact contact){
		Uri rslt =null;
		if(contact!=null && contact.getPhone()!=null && contact.getPhone().size()>0){
			Phone phone = contact.getPhone().get(0);
			if(phone!=null && !TextUtils.isEmpty(phone.getNumber())){
				Uri uri = Uri.parse("content://icc/adn"); 
				ContentValues values = null;
				values = new ContentValues();
				values.put("tag", TextUtils.isEmpty(contact.getDisplayName())?phone.getNumber():contact.getDisplayName());
				values.put("number", phone.getNumber());
				rslt = cr.insert(uri, values);
			}
		}
		return rslt;
	}
	
//	public int deleteSIMContactsByNumber(ContactList contacts) {
//		int rslt =0;
//		if(contacts!=null && contacts.getContacts()!=null && contacts.getContacts().size()>0){
//			Uri uri = Uri.parse("content://icc/adn"); 
//			
//			StringBuffer whereBuff = new StringBuffer();
//			ArrayList<String> argsList = new ArrayList<String>();
//			int counter = 0;
//			for (int i = 0; i < contacts.getContacts().size(); i++) {
//				Contact contact = contacts.getContacts().get(i);
//				
//				if(contact.getPhone()!=null && contact.getPhone().size()>0){
//					Phone phone = contact.getPhone().get(0);
//					if(phone!=null && !TextUtils.isEmpty(phone.getNumber())
//						//&& !argsList.contains(phone.getNumber())
//					){
//						if(counter==0){
//							whereBuff.append("number = ? ");
//						}else{
//							whereBuff.append(" OR number = ? ");
//						}
//						
//						argsList.add(phone.getNumber());
//						
//						counter++;
//					}
//				}
//			}
//			
//			if(argsList.size()>0){
//				String where = whereBuff.toString();
//				String whereArgs[] =new String[argsList.size()];
//				argsList.toArray(whereArgs);
//				Log.d(where);
//				Log.d(whereArgs.toString());
//				rslt = cr.delete(uri, where, whereArgs);
//			}
//		}
//		return rslt;
//	}
//	
//	public int deleteSIMContactsByName(ContactList contacts) {
//		int rslt =0;
//		if(contacts!=null && contacts.getContacts()!=null && contacts.getContacts().size()>0){
//			Uri uri = Uri.parse("content://icc/adn"); 
//			
//			StringBuffer whereBuff = new StringBuffer();
//			ArrayList<String> argsList = new ArrayList<String>();
//			int counter = 0;
//			for (int i = 0; i < contacts.getContacts().size(); i++) {
//				Contact contact = contacts.getContacts().get(i);
//				
////				if(!TextUtils.isEmpty(contact.getDisplayName())){
////					continue;
////				}
//				
//				String contactName  = contact.getDisplayName()==null?"null":contact.getDisplayName();
//				if(argsList.contains(contactName)){
//					continue;
//				}
//				
////				if(contact.getDisplayName()==null){
////					if(counter==0){
////						whereBuff.append("tag IS NULL ");
////					}else{
////						whereBuff.append(" OR tag IS NULL ");
////					}
////				}else{
//					if(counter==0){
//						whereBuff.append("tag = ? ");
//					}else{
//						whereBuff.append(" OR tag = ? ");
//					}
////				}
//				
//				argsList.add(contactName);
//				counter++;
//			}
//			
//			String where = whereBuff.toString();
//			if(where.length()>0){
//				Log.d(where);
//				
//				//argsList.remove(null);
//				String whereArgs[] =null;
//				if(argsList.size()>0){
//					whereArgs = new String[argsList.size()];
//					argsList.toArray(whereArgs);
//				}
//				
//				rslt = cr.delete(uri, where, whereArgs);
//			}
//		}
//		return rslt;
//	}
	
	private int deleteByNameAndNumber(ContactList contacts){
        int rslt =0;
		if(contacts!=null && contacts.getContacts()!=null && contacts.getContacts().size()>0){
			for (Contact contact : contacts.getContacts()) {
				rslt += deleteByNameAndNumber(contact);
			}
		}
		return rslt;	
	}
	/***
	 * delete success return 1,others return 0
	 * @param contact
	 * @return
	 */
	private int deleteByNameAndNumber(Contact contact){
        int rslt =0;
		if(contact!=null){
			Uri uri = Uri.parse("content://icc/adn"); 
			String contactName  = contact.getDisplayName()==null?"null":contact.getDisplayName();
			String where = "tag= '" + contactName + "'";
			if(contact.getPhone()!=null && contact.getPhone().size()>0){
				Phone phone = contact.getPhone().get(0);
				if(phone!=null && !TextUtils.isEmpty(phone.getNumber())){
					where += " AND number = '" + phone.getNumber() + "'";
				}
			}
			rslt += cr.delete(uri, where, null);
		}
		return rslt;	
	}
	
	public ContactList newContactList() {
		ContactList contacts = new ContactList();
		String id;

		Cursor cur = this.cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
		if (cur.getCount() > 0) {
			while (cur.moveToNext()) {
				Contact c = new Contact();
				id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
				c.setId(id);
				c.setDisplayName(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
				if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
					c.setPhone(this.getPhoneNumbers(id));
				}
				c.setEmail(this.getEmailAddresses(id));
				c.setNotes(this.getContactNotes(id));
				c.setAddresses(this.getContactAddresses(id));
				c.setImAddresses(this.getIM(id));
				c.setOrganization(this.getContactOrg(id));
				contacts.addContact(c);
			}
		}
		if(cur!=null){
			cur.close();
		}
		return contacts;
	}

	public ArrayList<Phone> getPhoneNumbers(String id) {
		ArrayList<Phone> phones = new ArrayList<Phone>();

		Cursor pCur = this.cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
				ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
		while (pCur.moveToNext()) {
			phones.add(new Phone(pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)),
					pCur.getInt(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE))));

		}
		if(pCur!=null){
			pCur.close();
		}
		return (phones);
	}

	public ArrayList<Email> getEmailAddresses(String id) {
		ArrayList<Email> emails = new ArrayList<Email>();

		Cursor emailCur = this.cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
				ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] { id }, null);
		while (emailCur.moveToNext()) {
			// This would allow you get several email addresses
			Email e = new Email(
					emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)),
					emailCur.getInt(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE)));
			emails.add(e);
		}
		if(emailCur!=null){
			emailCur.close();
		}
		return (emails);
	}

	public ArrayList<String> getContactNotes(String id) {
		ArrayList<String> notes = new ArrayList<String>();
		String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
		String[] whereParameters = new String[] { id, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE };
		Cursor noteCur = this.cr.query(ContactsContract.Data.CONTENT_URI, null, where, whereParameters, null);
		if (noteCur.moveToFirst()) {
			String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
			if (note.length() > 0) {
				notes.add(note);
			}
		}
		if(noteCur!=null){
			noteCur.close();
		}
		return (notes);
	}

	public ArrayList<Address> getContactAddresses(String id) {
		ArrayList<Address> addrList = new ArrayList<Address>();

		String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
		String[] whereParameters = new String[] { id,
				ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };

		Cursor addrCur = this.cr.query(ContactsContract.Data.CONTENT_URI, null, where, whereParameters, null);
		while (addrCur.moveToNext()) {
			String poBox = addrCur.getString(addrCur
					.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
			String street = addrCur.getString(addrCur
					.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
			String city = addrCur.getString(addrCur
					.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
			String region = addrCur.getString(addrCur
					.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
			String postalCode = addrCur.getString(addrCur
					.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
			String country = addrCur.getString(addrCur
					.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
			int type = addrCur.getInt(addrCur
					.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
			Address a = new Address(poBox, street, city, region, postalCode, country, type);
			addrList.add(a);
		}
		if(addrCur!=null){
			addrCur.close();
		}
		return (addrList);
	}

	public ArrayList<IM> getIM(String id) {
		ArrayList<IM> imList = new ArrayList<IM>();
		String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
		String[] whereParameters = new String[] { id, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE };

		Cursor imCur = this.cr.query(ContactsContract.Data.CONTENT_URI, null, where, whereParameters, null);
		if (imCur.moveToFirst()) {
			String imName = imCur.getString(imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
			int imType = imCur.getInt(imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE));
			if (imName.length() > 0) {
				IM im = new IM(imName, imType);
				imList.add(im);
			}
		}
		if(imCur!=null)
			imCur.close();
		return (imList);
	}

	public Organization getContactOrg(String id) {
		Organization org = new Organization();
		String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
		String[] whereParameters = new String[] { id, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE };

		Cursor orgCur = this.cr.query(ContactsContract.Data.CONTENT_URI, null, where, whereParameters, null);

		if (orgCur.moveToFirst()) {
			String orgName = orgCur
					.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
			String title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
			if (orgName.length() > 0) {
				org.setOrganization(orgName);
				org.setTitle(title);
			}
		}
		if(orgCur!=null)orgCur.close();
		return (org);
	}
	
	public Contact getContactById(String id) {
		Contact c =null;
		if(!TextUtils.isEmpty(id)){
			Cursor cur = this.cr.query(ContactsContract.Contacts.CONTENT_URI, null, ContactsContract.Contacts._ID + " = ?", new String[]{id}, null);
			if (cur.getCount() > 0) {
				while(cur.moveToNext()){
					c = new Contact();
					id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
					c.setId(id);
					c.setDisplayName(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
					if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
						c.setPhone(this.getPhoneNumbers(id));
					}
					c.setEmail(this.getEmailAddresses(id));
					c.setNotes(this.getContactNotes(id));
					c.setAddresses(this.getContactAddresses(id));
					c.setImAddresses(this.getIM(id));
					c.setOrganization(this.getContactOrg(id));
					break;
				}
			}
			if(cur!=null){
				cur.close();
			}
		}
		return c;
	}
	public Contact getContactByPhoneNumber(String phoneNum) {
		Contact c =null;
		if(!TextUtils.isEmpty(phoneNum)){
			
			Cursor pCur = this.cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI
									, new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID}
									, ContactsContract.CommonDataKinds.Phone.NUMBER + " = ? or " 
											+ContactsContract.CommonDataKinds.Phone.NUMBER + " = ? "
									, new String[] { phoneNum,"+86"+phoneNum }, null);
			int contactid = -1;
			if(pCur!=null && pCur.getCount()>0){
				while (pCur.moveToNext()) {
					contactid = pCur.getInt(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
					break;
				}
			}
			if(pCur!=null){
				pCur.close();
			}
			
			if(contactid>=0){
				Cursor cur = this.cr.query(ContactsContract.Contacts.CONTENT_URI, null, ContactsContract.Contacts._ID + " = ?", new String[]{String.valueOf(contactid)}, null);
				if (cur.getCount() > 0) {
					while(cur.moveToNext()){
						c = new Contact();
						String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
						c.setId(id);
						c.setDisplayName(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
						if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
							c.setPhone(this.getPhoneNumbers(id));
						}
						c.setEmail(this.getEmailAddresses(id));
						c.setNotes(this.getContactNotes(id));
						c.setAddresses(this.getContactAddresses(id));
						c.setImAddresses(this.getIM(id));
						c.setOrganization(this.getContactOrg(id));
						break;
					}
				}
				if(cur!=null){
					cur.close();
				}
			}
		}
		return c;
	}

	public int converContactToSIMCard(){
		ContactList contacList = newContactList();
		return addSIMContacts(contacList);
	}
	
	public int deleteSIMContacts(){
		ContactList contacList = getSIMContactList();
		return deleteByNameAndNumber(contacList);
	}
}